package pe.com.bbva.ge.vista.vaadin.ui;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import pe.com.bbva.ge.domain.quartz.QrtzCronTriggers;
import pe.com.bbva.ge.domain.quartz.QrtzJobDetails;
import pe.com.bbva.ge.domain.quartz.QrtzTriggers;
import pe.com.bbva.ge.persistencia.orm.ConfiguracionORM;
import pe.com.bbva.ge.persistencia.orm.hibernate.ConfiguracionORMHibernate;
import pe.com.bbva.ge.vista.vaadin.ui.utileria.ConfirmDialog;
import pe.com.bbva.ge.vista.vaadin.ui.utileria.ContextoTareas;
import pe.com.bbva.ge.vista.vaadin.ui.utileria.Inject;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.AbstractBeanContainer.BeanIdResolver;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.event.ShortcutAction;
import com.vaadin.event.ShortcutListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.Notification;

public class ProgramadorTareasUI extends CustomComponent implements ClickListener, ValueChangeListener{
	
	Logger logger = LogManager.getLogger(ProgramadorTareasUI.class.getName());

	@AutoGenerated
	private VerticalLayout mainLayout;
	
	@AutoGenerated
	private VerticalLayout panelContenedor;
	
	@AutoGenerated
	private VerticalLayout panelSeparador;

	@AutoGenerated
	private Table tblJob;
	
	@AutoGenerated
	private Table tblTrigger;
	
	@AutoGenerated
	private HorizontalLayout panelFiltroJob;
	
	@AutoGenerated
	private HorizontalLayout panelFiltroTrigger;

	@AutoGenerated
	private TextField txtFiltroGrupoJob;
	
	@AutoGenerated
	private TextField txtGrupoJob;
	
	@AutoGenerated
	private TextField txtNombreJob;
	
	@AutoGenerated
	private TextField txtDescripcionJob;
	
	@AutoGenerated
	private TextField txtClaseJob;
	
	@AutoGenerated
	private TextField txtFiltroNombreJob;

	@AutoGenerated
	private TextField txtFiltroDescripcionJob;

	@AutoGenerated
	private TextField txtFiltroClaseJob;
	
	@AutoGenerated
	private HorizontalLayout panelBotonesContenidoJob;

	@AutoGenerated
	private HorizontalLayout panelBotonesContenidoTrigger;
	
	@AutoGenerated
	private TextField txtFiltroGrupoTrigger;

	@AutoGenerated
	private TextField txtFiltroTipoTrigger;

	@AutoGenerated
	private TextField txtFiltroNombreTrigger;

	@AutoGenerated
	private TextField txtFiltroPrioridadTrigger;

	@AutoGenerated
	private TextField txtFiltroExpresionTrigger;

	@AutoGenerated
	private TextField txtFiltroInicioTrigger;
	
	@AutoGenerated
	private TextField txtFiltroTerminoTrigger;

	@AutoGenerated
	private TextField txtFiltroUltEjecTrigger;

	@AutoGenerated
	private TextField txtFiltroSigEjecTrigger;

	@AutoGenerated
	private TextField txtFiltroEstadoTrigger;

	@AutoGenerated
	private HorizontalLayout panelBotonScheduler;
	
	@AutoGenerated
	private Button btnActualizarEstado;

	@AutoGenerated
	private Button btnIniciarScheduler;
	
	@AutoGenerated
	private Button btnDetenerScheduler;
	
	@AutoGenerated
	private HorizontalLayout panelJob;
	
	@AutoGenerated
	private VerticalLayout panelTablaJob;
	
	@AutoGenerated
	private VerticalLayout panelTablaTrigger;
	
	@AutoGenerated
	private VerticalLayout panelDatosJob;
	
	@AutoGenerated
	private VerticalLayout panelDatosTrigger;
	
	@AutoGenerated
	private HorizontalLayout panelTrigger;
	
	@AutoGenerated
	private Button btnGrabarJob;
	
	@AutoGenerated
	private Button btnEliminarJob;
	
	@AutoGenerated
	private Button btnEjecutarJob;
	
	@AutoGenerated
	private Button btnEjecutarTrigger;
	
	@AutoGenerated
	private Button btnGrabarTrigger;
	
	@AutoGenerated
	private Button btnEliminarTrigger;
	
	@AutoGenerated
	private Label lblEtiquetaJob;
	
	@AutoGenerated
	private Label lblEtiquetaTrigger;
	
	
	@AutoGenerated
	private TextField txtGrupoTrigger;
	
	@AutoGenerated
	private TextField txtTipoTrigger;
	
	@AutoGenerated
	private TextField txtNombreTrigger;
	
	@AutoGenerated
	private TextField txtPrioridadTrigger;

	@AutoGenerated
	private TextField txtExpresionTrigger;
	
	@AutoGenerated
	private TextField txtInicioTrigger;
	
	@AutoGenerated
	private TextField txtTerminoTrigger;
	
	@AutoGenerated
	private TextField txtUltEjecTrigger;
	
	@AutoGenerated
	private TextField txtSigEjecTrigger;
	
	@AutoGenerated
	private TextField txtEstadoTrigger;
	
	private boolean flagNuevoJob;
	
	private boolean flagNuevoTrigger;
	
	@Autowired
	private ConfiguracionORM genericoORM;

	private ApplicationContext contexto;
	
	ContextoTareas ctx = ContextoTareas.getInstance();
	
	private Scheduler scheduler;
	
	private static final String JOB = "JOB";
	
	private static final String TRIGGER = "TRIGGER";
	
	
	private static final long serialVersionUID = -4704033675557810377L;

	public ProgramadorTareasUI() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
		postConstruct();
	}
	
	public void postConstruct(){
		Inject.inject(this);		
		contexto = ctx.obtenerContexto();
    	scheduler = (Scheduler) contexto.getBean("quartzScheduler");
    	
    	validarScheduler();
    	
		habilitarEdicionJob(false);
		cargarTablaJob(null);
	}
	
	
	@AutoGenerated
	private VerticalLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new VerticalLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(false);
		
		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");
		
		// tabBandeja
		panelContenedor = builPanelContenedor();
		
		mainLayout.addComponent(panelContenedor);
		
		return mainLayout;
	}

	@AutoGenerated
	private VerticalLayout builPanelContenedor() {
		// common part: create layout
		panelContenedor = new VerticalLayout();
		panelContenedor.setImmediate(true);
		panelContenedor.setWidth("100.0%");
		panelContenedor.setHeight("-1px");
		
		panelBotonScheduler = buildPanelBotonScheduler();
		panelSeparador = buildPanelSeparador();
		panelJob = buildPanelJob();
		panelSeparador = buildPanelSeparador();
		panelTrigger = buildPanelTrigger();
		
		panelContenedor.addComponent(panelBotonScheduler);
		panelContenedor.addComponent(panelSeparador);
		panelContenedor.addComponent(panelJob);
		panelContenedor.addComponent(panelSeparador);
		panelContenedor.addComponent(panelTrigger);
		
		return panelContenedor;
	}
	
	private VerticalLayout buildPanelSeparador(){
		panelSeparador = new VerticalLayout();
		panelSeparador.setImmediate(true);
		panelSeparador.setWidth("100.0%");
		panelSeparador.setHeight("15px");
		panelSeparador.setMargin(false);
		panelSeparador.setSpacing(true);
		
		return panelSeparador;
	}
	
	private HorizontalLayout buildPanelJob(){
		panelJob = new HorizontalLayout();
		panelJob.setImmediate(false);
		panelJob.setWidth("1200px"); //70.0%
		panelJob.setHeight("-1px");
		panelJob.setMargin(false);
		panelJob.setSpacing(true);
		
		panelTablaJob = buildPanelTablaJob();
//		panelSeparador = buildPanelSeparador();
		panelDatosJob = buildPanelDatosJob();
		
		panelJob.addComponent(panelTablaJob);
//		panelJob.addComponent(panelSeparador);
		panelJob.addComponent(panelDatosJob);
		
		return panelJob;
	}

	private HorizontalLayout buildPanelTrigger(){
		panelTrigger = new HorizontalLayout();
		panelTrigger.setImmediate(false);
		panelTrigger.setWidth("1300px"); //70.0%
		panelTrigger.setHeight("-1px");
		panelTrigger.setMargin(false);
		panelTrigger.setSpacing(true);
		panelTrigger.setVisible(false);
		
		panelTablaTrigger = buildPanelTablaTrigger();
		panelDatosTrigger = buildPanelDatosTrigger();

		panelTrigger.addComponent(panelTablaTrigger);
		panelTrigger.addComponent(panelDatosTrigger);
		
		return panelTrigger;
	}
	
	
	private VerticalLayout buildPanelTablaJob(){
		panelTablaJob = new VerticalLayout();
		panelTablaJob.setImmediate(false);
		panelTablaJob.setWidth("870px"); //860px
		panelTablaJob.setHeight("-1px");
		panelTablaJob.setMargin(false);
		panelTablaJob.setSpacing(true);
		
		//lblEtiquetaJob
		lblEtiquetaJob = new Label();
		lblEtiquetaJob.setValue("Tareas (Job)");
		lblEtiquetaJob.setImmediate(false);
		lblEtiquetaJob.setWidth("-1px");
		lblEtiquetaJob.setHeight("-1px");
		
		//panelFiltroJob
		panelFiltroJob = buildPanelFiltroJob();
		
		//tblJob
		tblJob = new Table();
		//tblJob.setCaption("Tareas (Jobs)");
		tblJob.setImmediate(true);
		tblJob.setWidth("865px"); //860px
		tblJob.setHeight("-1px");
		tblJob.setSelectable(true);
		tblJob.setColumnCollapsingAllowed(false);
		tblJob.setColumnReorderingAllowed(false);
		tblJob.addListener((ValueChangeListener) this);
		
		panelTablaJob.addComponent(lblEtiquetaJob);
		panelTablaJob.addComponent(panelFiltroJob);
		panelTablaJob.addComponent(tblJob);
		
		return panelTablaJob;
	}
	
	private VerticalLayout buildPanelTablaTrigger(){
		panelTablaTrigger = new VerticalLayout();
		panelTablaTrigger.setImmediate(false);
		panelTablaTrigger.setWidth("965px"); //860px
		panelTablaTrigger.setHeight("-1px");
		panelTablaTrigger.setMargin(false);
		panelTablaTrigger.setSpacing(true);
		
		//lblEtiquetaTrigger
		lblEtiquetaTrigger = new Label();
		lblEtiquetaTrigger.setValue("Programaciones (Triggers)");
		lblEtiquetaTrigger.setImmediate(false);
		lblEtiquetaTrigger.setWidth("-1px");
		lblEtiquetaTrigger.setHeight("-1px");
		
		//panelFiltroTrigger
		panelFiltroTrigger = buildPanelFiltroTrigger();
		
		//tblTrigger
		tblTrigger = new Table();
		//tblJob.setCaption("Tareas (Jobs)");
		tblTrigger.setImmediate(true);
		tblTrigger.setWidth("960px"); //860px   865
		tblTrigger.setHeight("-1px");
		tblTrigger.setSelectable(true);
		tblTrigger.setColumnCollapsingAllowed(false);
		tblTrigger.setColumnReorderingAllowed(false);
		tblTrigger.addListener(new ValueChangeListener() {
			private static final long serialVersionUID = 8766174414524651740L;

//			@Override
			public void valueChange(ValueChangeEvent event) {
				boolean esModoNuevoTrigger = tblTrigger.getValue() == null;	
				valueChangeTrigger(esModoNuevoTrigger);	
			}
		});

//		tblTrigger.addListener((ValueChangeListener) this);
		
		panelTablaTrigger.addComponent(lblEtiquetaTrigger);
		panelTablaTrigger.addComponent(panelFiltroTrigger);
		panelTablaTrigger.addComponent(tblTrigger);
		
		return panelTablaTrigger;		
	}
	
	private VerticalLayout buildPanelDatosJob(){
		panelDatosJob = new VerticalLayout();
		panelDatosJob.setImmediate(false);
		panelDatosJob.setWidth("300px"); //200px
		panelDatosJob.setHeight("-1px");
		panelDatosJob.setMargin(false);
		
		panelSeparador = buildPanelSeparador();
		panelDatosJob.addComponent(panelSeparador);
		
		txtGrupoJob = new TextField();
		txtGrupoJob.setStyleName("fieldRequired");
		txtGrupoJob.setCaption(" ");
		txtGrupoJob.setImmediate(false);
		txtGrupoJob.setWidth("200px");
		txtGrupoJob.setHeight("-1px");
		txtGrupoJob.setInputPrompt("Grupo");
		txtGrupoJob.setRequired(true);
		panelDatosJob.addComponent(txtGrupoJob);
		
		txtNombreJob = new TextField();
		txtNombreJob.setStyleName("fieldRequired");
		txtNombreJob.setCaption(" ");
		txtNombreJob.setImmediate(false);
		txtNombreJob.setWidth("200px");
		txtNombreJob.setHeight("-1px");
		txtNombreJob.setInputPrompt("Nombre");
		txtNombreJob.setRequired(true);
		panelDatosJob.addComponent(txtNombreJob);
		
		txtDescripcionJob = new TextField();
//		txtDescripcionJob.setStyleName("fieldRequired");
		txtDescripcionJob.setCaption(" ");
		txtDescripcionJob.setImmediate(false);
		txtDescripcionJob.setWidth("270px");
		txtDescripcionJob.setHeight("-1px");
		txtDescripcionJob.setInputPrompt("Descripción");
		panelDatosJob.addComponent(txtDescripcionJob);
		
		txtClaseJob = new TextField();
		txtClaseJob.setStyleName("fieldRequired");
		txtClaseJob.setCaption(" ");
		txtClaseJob.setImmediate(false);
		txtClaseJob.setWidth("270px");
		txtClaseJob.setHeight("-1px");
		txtClaseJob.setInputPrompt("Clase");
		txtClaseJob.setRequired(true);
		panelDatosJob.addComponent(txtClaseJob);
		
		panelSeparador = buildPanelSeparador();
		panelDatosJob.addComponent(panelSeparador);
		
		panelBotonesContenidoJob = buildPanelBotonesContenidoJob();
		panelDatosJob.addComponent(panelBotonesContenidoJob);
		
		return panelDatosJob;
	}
	
	
	private VerticalLayout buildPanelDatosTrigger(){
		panelDatosTrigger = new VerticalLayout();
		panelDatosTrigger.setImmediate(false);
		panelDatosTrigger.setWidth("300px"); //200px
		panelDatosTrigger.setHeight("-1px");
		panelDatosTrigger.setMargin(false);
		
		panelSeparador = buildPanelSeparador();
		panelDatosTrigger.addComponent(panelSeparador);
		
		txtGrupoTrigger = new TextField();
		txtGrupoTrigger.setStyleName("fieldRequired");
		txtGrupoTrigger.setCaption(" ");
		txtGrupoTrigger.setImmediate(false);
		txtGrupoTrigger.setWidth("180px");
		txtGrupoTrigger.setHeight("-1px");
		txtGrupoTrigger.setInputPrompt("Grupo");
		txtGrupoTrigger.setRequired(true);
		panelDatosTrigger.addComponent(txtGrupoTrigger);
		
		txtNombreTrigger = new TextField();
		txtNombreTrigger.setStyleName("fieldRequired");
		txtNombreTrigger.setCaption(" ");
		txtNombreTrigger.setImmediate(false);
		txtNombreTrigger.setWidth("200px");
		txtNombreTrigger.setHeight("-1px");
		txtNombreTrigger.setInputPrompt("Nombre");
		txtNombreTrigger.setRequired(true);
		panelDatosTrigger.addComponent(txtNombreTrigger);
		
		txtPrioridadTrigger = new TextField();
		txtPrioridadTrigger.setStyleName("fieldRequired");
		txtPrioridadTrigger.setCaption(" ");
		txtPrioridadTrigger.setImmediate(false);
		txtPrioridadTrigger.setWidth("120px");
		txtPrioridadTrigger.setHeight("-1px");
		txtPrioridadTrigger.setInputPrompt("Prioridad");
		txtPrioridadTrigger.setRequired(true);
		panelDatosTrigger.addComponent(txtPrioridadTrigger);
		
		txtExpresionTrigger = new TextField();
		txtExpresionTrigger.setStyleName("fieldRequired");
		txtExpresionTrigger.setCaption(" ");
		txtExpresionTrigger.setImmediate(false);
		txtExpresionTrigger.setWidth("270px");
		txtExpresionTrigger.setHeight("-1px");
		txtExpresionTrigger.setRequired(true);
		txtExpresionTrigger.setInputPrompt("ExpresiÃ³n");
		panelDatosTrigger.addComponent(txtExpresionTrigger);
		
		panelSeparador = buildPanelSeparador();
		panelDatosTrigger.addComponent(panelSeparador);
		
		panelBotonesContenidoTrigger = buildPanelBotonesContenidoTrigger();
		panelDatosTrigger.addComponent(panelBotonesContenidoTrigger);
		
		return panelDatosTrigger;
	}
	
	private HorizontalLayout buildPanelBotonesContenidoJob(){
		panelBotonesContenidoJob = new HorizontalLayout();
		panelBotonesContenidoJob.setImmediate(false);
		panelBotonesContenidoJob.setWidth("300px");
		panelBotonesContenidoJob.setHeight("-1px"); //51px
		panelBotonesContenidoJob.setMargin(false);
		
		// btnGrabarJob
		btnGrabarJob = new Button();
		btnGrabarJob.setCaption("Crear");
		btnGrabarJob.setImmediate(true);
		btnGrabarJob.setWidth("-1px");
		btnGrabarJob.setHeight("-1px");
		btnGrabarJob.addListener((ClickListener) this);
		panelBotonesContenidoJob.addComponent(btnGrabarJob);
		panelBotonesContenidoJob.setComponentAlignment(btnGrabarJob,
						new Alignment(9));
		
		//btnEliminarJob
		btnEliminarJob = new Button();
		btnEliminarJob.setCaption("Eliminar");
		btnEliminarJob.setImmediate(true);
		btnEliminarJob.setWidth("-1px");
		btnEliminarJob.setHeight("-1px");
		btnEliminarJob.addListener((ClickListener) this);
		panelBotonesContenidoJob.addComponent(btnEliminarJob);
		panelBotonesContenidoJob.setComponentAlignment(btnEliminarJob,
						new Alignment(10));
		
		//btnEjecutarJob
		btnEjecutarJob = new Button();
		btnEjecutarJob.setCaption("Ejecutar");
		btnEjecutarJob.setImmediate(true);
		btnEjecutarJob.setWidth("-1px");
		btnEjecutarJob.setHeight("-1px");
		btnEjecutarJob.addListener((ClickListener) this);
		panelBotonesContenidoJob.addComponent(btnEjecutarJob);
		panelBotonesContenidoJob.setComponentAlignment(btnEjecutarJob,
						new Alignment(11));
		
		return panelBotonesContenidoJob;
	}
	
	private HorizontalLayout buildPanelBotonesContenidoTrigger(){
		panelBotonesContenidoTrigger = new HorizontalLayout();
		panelBotonesContenidoTrigger.setImmediate(false);
		panelBotonesContenidoTrigger.setWidth("300px");
		panelBotonesContenidoTrigger.setHeight("-1px"); //51px
		panelBotonesContenidoTrigger.setMargin(false);
		
		// btnGrabarTrigger
		btnGrabarTrigger = new Button();
		btnGrabarTrigger.setCaption("Crear");
		btnGrabarTrigger.setImmediate(true);
		btnGrabarTrigger.setWidth("-1px");
		btnGrabarTrigger.setHeight("-1px");
		btnGrabarTrigger.addListener((ClickListener) this);
		panelBotonesContenidoTrigger.addComponent(btnGrabarTrigger);
		panelBotonesContenidoTrigger.setComponentAlignment(btnGrabarTrigger,
						new Alignment(9));
		
		//btnEliminarTrigger
		btnEliminarTrigger = new Button();
		btnEliminarTrigger.setCaption("Eliminar");
		btnEliminarTrigger.setImmediate(true);
		btnEliminarTrigger.setWidth("-1px");
		btnEliminarTrigger.setHeight("-1px");
		btnEliminarTrigger.addListener((ClickListener) this);
		panelBotonesContenidoTrigger.addComponent(btnEliminarTrigger);
		panelBotonesContenidoTrigger.setComponentAlignment(btnEliminarTrigger,
						new Alignment(10));
		
		//btnEjecutarJob
		btnEjecutarTrigger = new Button();
		btnEjecutarTrigger.setCaption("Ejecutar");
		btnEjecutarTrigger.setImmediate(true);
		btnEjecutarTrigger.setWidth("-1px");
		btnEjecutarTrigger.setHeight("-1px");
		btnEjecutarTrigger.addListener((ClickListener) this);
		panelBotonesContenidoTrigger.addComponent(btnEjecutarTrigger);
		panelBotonesContenidoTrigger.setComponentAlignment(btnEjecutarTrigger,
						new Alignment(11));
		
		return panelBotonesContenidoTrigger;
	}
	
	private HorizontalLayout buildPanelFiltroJob(){
		panelFiltroJob = new HorizontalLayout();
		panelFiltroJob.setImmediate(false);
		panelFiltroJob.setWidth("865px"); //860px
		panelFiltroJob.setHeight("-1px");
		panelFiltroJob.setMargin(false);
		panelFiltroJob.setSpacing(true);
		
		txtFiltroGrupoJob = new TextField();
		txtFiltroGrupoJob.setImmediate(false);
		txtFiltroGrupoJob.setInputPrompt("Grupo");
		txtFiltroGrupoJob.setWidth("115px");
		txtFiltroGrupoJob.setHeight("-1px");
		txtFiltroGrupoJob.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosJob();
			}
		});
		
		panelFiltroJob.addComponent(txtFiltroGrupoJob);
//		panelFiltroJob.setComponentAlignment(txtFiltroGrupoJob, new Alignment(9));
				
		
		txtFiltroNombreJob = new TextField();
		txtFiltroNombreJob.setImmediate(false);
		txtFiltroNombreJob.setWidth("143px");
		txtFiltroNombreJob.setHeight("-1px");
		txtFiltroNombreJob.setInputPrompt("Nombre");
		txtFiltroNombreJob.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosJob();
			}
		});
		panelFiltroJob.addComponent(txtFiltroNombreJob);
//		panelFiltroJob.setComponentAlignment(txtFiltroNombreJob, new Alignment(9));
		
		txtFiltroDescripcionJob = new TextField();
		txtFiltroDescripcionJob.setImmediate(false);
		txtFiltroDescripcionJob.setWidth("285px");
		txtFiltroDescripcionJob.setHeight("-1px");
		txtFiltroDescripcionJob.setInputPrompt("Descripción");
		txtFiltroDescripcionJob.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosJob();
			}
		});
		panelFiltroJob.addComponent(txtFiltroDescripcionJob);
//		panelFiltroJob.setComponentAlignment(txtFiltroDescripcionJob, new Alignment(9));
		
		txtFiltroClaseJob = new TextField();
		txtFiltroClaseJob.setImmediate(false);
		txtFiltroClaseJob.setWidth("290px");
		txtFiltroClaseJob.setHeight("-1px");
		txtFiltroClaseJob.setInputPrompt("Clase");
		txtFiltroClaseJob.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosJob();
			}
		});
		panelFiltroJob.addComponent(txtFiltroClaseJob);
//		panelFiltroJob.setComponentAlignment(txtFiltroClaseJob, new Alignment(9));
		
		return panelFiltroJob;
	}
	
	private HorizontalLayout buildPanelFiltroTrigger(){
		panelFiltroTrigger = new HorizontalLayout();
		panelFiltroTrigger.setImmediate(false);
		panelFiltroTrigger.setWidth("960px"); //860px
		panelFiltroTrigger.setHeight("-1px");
		panelFiltroTrigger.setMargin(false);
		panelFiltroTrigger.setSpacing(true);
		
		//txtFiltroGrupoTrigger
		txtFiltroGrupoTrigger = new TextField();
		txtFiltroGrupoTrigger.setImmediate(false);
		txtFiltroGrupoTrigger.setInputPrompt("Grupo");
		txtFiltroGrupoTrigger.setWidth("55px");
		txtFiltroGrupoTrigger.setHeight("-1px");
		txtFiltroGrupoTrigger.addShortcutListener(new ShortcutListener("Filtrar Trigger", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				// TODO Auto-generated method stub
				
			}
		});
		/*txtFiltroGrupoTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosJob();
			}
		});*/
		panelFiltroTrigger.addComponent(txtFiltroGrupoTrigger);
		
		//txtFiltroTipoTrigger
		txtFiltroTipoTrigger = new TextField();
		txtFiltroTipoTrigger.setImmediate(false);
		txtFiltroTipoTrigger.setWidth("40px");
		txtFiltroTipoTrigger.setHeight("-1px");
		txtFiltroTipoTrigger.setInputPrompt("Tipo");
		txtFiltroTipoTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroTipoTrigger);
		
		//txtFiltroNombreTrigger
		txtFiltroNombreTrigger = new TextField();
		txtFiltroNombreTrigger.setImmediate(false);
		txtFiltroNombreTrigger.setWidth("70px");
		txtFiltroNombreTrigger.setHeight("-1px");
		txtFiltroNombreTrigger.setInputPrompt("Nombre");
		txtFiltroNombreTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroNombreTrigger);
		
		//txtFiltroPrioridadTrigger
		txtFiltroPrioridadTrigger = new TextField();
		txtFiltroPrioridadTrigger.setImmediate(false);
		txtFiltroPrioridadTrigger.setWidth("30px");
		txtFiltroPrioridadTrigger.setHeight("-1px");
		txtFiltroPrioridadTrigger.setInputPrompt("Prio");
		txtFiltroPrioridadTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroPrioridadTrigger);
		
		
		//txtFiltroExpresionTrigger
		txtFiltroExpresionTrigger = new TextField();
		txtFiltroExpresionTrigger.setImmediate(false);
		txtFiltroExpresionTrigger.setWidth("117px");
		txtFiltroExpresionTrigger.setHeight("-1px");
		txtFiltroExpresionTrigger.setInputPrompt("Expresión");
		txtFiltroExpresionTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroExpresionTrigger);
		
		
		//txtFiltroInicioTrigger
		txtFiltroInicioTrigger = new TextField();
		txtFiltroInicioTrigger.setImmediate(false);
		txtFiltroInicioTrigger.setWidth("122px");
		txtFiltroInicioTrigger.setHeight("-1px");
		txtFiltroInicioTrigger.setInputPrompt("Inicio");
		txtFiltroInicioTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroInicioTrigger);
		
		
		//txtFiltroTerminoTrigger
		txtFiltroTerminoTrigger = new TextField();
		txtFiltroTerminoTrigger.setImmediate(false);
		txtFiltroTerminoTrigger.setWidth("122px");
		txtFiltroTerminoTrigger.setHeight("-1px");
		txtFiltroTerminoTrigger.setInputPrompt("Término");
		txtFiltroTerminoTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroTerminoTrigger);
		
		
		//txtFiltroUltEjecTrigger
		txtFiltroUltEjecTrigger = new TextField();
		txtFiltroUltEjecTrigger.setImmediate(false);
		txtFiltroUltEjecTrigger.setWidth("122px");
		txtFiltroUltEjecTrigger.setHeight("-1px");
		txtFiltroUltEjecTrigger.setInputPrompt("Ult. Ejecución");
		txtFiltroUltEjecTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroUltEjecTrigger);
		
		
		//txtFiltroSigEjecTrigger
		txtFiltroSigEjecTrigger = new TextField();
		txtFiltroSigEjecTrigger.setImmediate(false);
		txtFiltroSigEjecTrigger.setWidth("122px");
		txtFiltroSigEjecTrigger.setHeight("-1px");
		txtFiltroSigEjecTrigger.setInputPrompt("Sig. Ejecución");
		txtFiltroSigEjecTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroSigEjecTrigger);
		
		
		//txtFiltroEstadoTrigger
		txtFiltroEstadoTrigger = new TextField();
		txtFiltroEstadoTrigger.setImmediate(false);
		txtFiltroEstadoTrigger.setWidth("78px");
		txtFiltroEstadoTrigger.setHeight("-1px");
		txtFiltroEstadoTrigger.setInputPrompt("Estado");
		txtFiltroEstadoTrigger.addShortcutListener(new ShortcutListener("Filtrar", ShortcutAction.KeyCode.ENTER, null) {
			@Override
			public void handleAction(Object sender, Object target) {
				buscarFiltrosTrigger();
			}
		});
		panelFiltroTrigger.addComponent(txtFiltroEstadoTrigger);
		
		return panelFiltroTrigger;
	}
	
	
	private HorizontalLayout buildPanelBotonScheduler(){
		panelBotonScheduler = new HorizontalLayout();
		panelBotonScheduler.setImmediate(true);
		panelBotonScheduler.setWidth("400px");
		panelBotonScheduler.setHeight("-1px"); //25px
		
		btnActualizarEstado = new Button();
		btnActualizarEstado.setCaption("Actualizar Estado");
		btnActualizarEstado.setImmediate(true);
		btnActualizarEstado.setWidth("-1px");
		btnActualizarEstado.setHeight("-1px");
		btnActualizarEstado.addListener((ClickListener)this);
		panelBotonScheduler.addComponent(btnActualizarEstado);
		
		btnIniciarScheduler = new Button();
		btnIniciarScheduler.setCaption("Iniciar Scheduler");
		btnIniciarScheduler.setImmediate(true);
		btnIniciarScheduler.setWidth("-1px");
		btnIniciarScheduler.setHeight("-1px");
		btnIniciarScheduler.addListener((ClickListener)this);
		panelBotonScheduler.addComponent(btnIniciarScheduler);
		
		btnDetenerScheduler = new Button();
		btnDetenerScheduler.setCaption("Detener Scheduler");
		btnDetenerScheduler.setImmediate(true);
		btnDetenerScheduler.setWidth("-1px");
		btnDetenerScheduler.setHeight("-1px");
		btnDetenerScheduler.addListener((ClickListener)this);
		panelBotonScheduler.addComponent(btnDetenerScheduler);
		
		return panelBotonScheduler;
	}

	private void cargarTablaJob(List<QrtzJobDetails> listaJob){
		
		List<QrtzJobDetails> lstJobs = null;
		
		if(listaJob!=null && !listaJob.isEmpty()){
			lstJobs = listaJob;
		}else{
			lstJobs = genericoORM.buscarJobDetails(null);
		}
		
		BeanContainer<String, QrtzJobDetails> container=new BeanContainer<String, QrtzJobDetails>(QrtzJobDetails.class);
		container.setBeanIdResolver(new BeanIdResolver<String, QrtzJobDetails>() {

			private static final long serialVersionUID = -5477745751697471304L;
			
//			@Override
			public String getIdForBean(QrtzJobDetails bean) {
				return bean.getJobName();
			}
			
		});
		container.addAll(lstJobs);
		container.setBeanIdProperty("jobName");
		
		/*tblJob.setContainerDataSource(container);
		tblJob.setVisibleColumns(new Object[]{"grupo", "nombre", "descripcion", "clase"});
		tblJob.setColumnWidth("grupo", 80);
		tblJob.setColumnWidth("nombre", 125);
		tblJob.setColumnWidth("descripcion", 250);
		tblJob.setColumnWidth("clase", 250);
		tblJob.setColumnHeader("grupo", "Grupo");
		tblJob.setColumnHeader("nombre", "Nombre");
		tblJob.setColumnHeader("descripcion", "DescripciÃ³n");
		tblJob.setColumnHeader("clase", "Clase");*/
		
		tblJob.setContainerDataSource(container);
		tblJob.setVisibleColumns(new Object[]{"jobGroup", "jobName", "description", "jobClassName"});
		/*tblJob.setColumnWidth("grupo", 80);
		tblJob.setColumnWidth("nombre", 125);
		tblJob.setColumnWidth("descripcion", 250);
		tblJob.setColumnWidth("clase", 250);*/
		tblJob.setColumnWidth("jobGroup", 100);
		tblJob.setColumnWidth("jobName", 140);
		tblJob.setColumnWidth("description", 280);
		tblJob.setColumnWidth("jobClassName", 290);
		tblJob.setColumnHeader("jobGroup", "Grupo");
		tblJob.setColumnHeader("jobName", "Nombre");
		tblJob.setColumnHeader("description", "Descripción");
		tblJob.setColumnHeader("jobClassName", "Clase");
		
	}
	
	private void cargarTablaTrigger(JobDetail jobDetail, boolean flagLimpiar, List<QrtzTriggers> lstTrigger, String cronExpresion){
		
		List<QrtzTriggers> listaTrigger = new ArrayList<QrtzTriggers>();
		
		if(jobDetail!=null){
			QrtzTriggers trig = new QrtzTriggers();
			trig.setJobGroup(jobDetail.getGroup());
			trig.setJobName(jobDetail.getName());
			
			if(lstTrigger!=null){
				listaTrigger = lstTrigger;
			}else{
				listaTrigger = genericoORM.buscarTriggers(trig);	
			}
		}
		
		IndexedContainer container = new IndexedContainer();
		container.addContainerProperty("grupo", String.class,  null);
		container.addContainerProperty("tipo", String.class,  null);
		container.addContainerProperty("nombre", String.class,  null);
		container.addContainerProperty("prioridad", Integer.class, null);
		container.addContainerProperty("expresion", String.class,  null);
		container.addContainerProperty("inicio", String.class,  null);
		container.addContainerProperty("termino", String.class, null);
		container.addContainerProperty("ultEjec", String.class, null);
		container.addContainerProperty("sigEjec", String.class, null);
		container.addContainerProperty("estado", String.class, null);
		
		
		tblTrigger.setContainerDataSource(container);
		tblTrigger.setVisibleColumns(new Object[]{"grupo", "tipo", "nombre", "prioridad", "expresion", "inicio", "termino", "ultEjec", "sigEjec", "estado"});
		tblTrigger.setColumnWidth("grupo", 40);
		tblTrigger.setColumnWidth("tipo", 35);
		tblTrigger.setColumnWidth("nombre", 70);
		tblTrigger.setColumnWidth("prioridad", 25);
		tblTrigger.setColumnWidth("expresion", 107);
		tblTrigger.setColumnWidth("inicio", 120);
		tblTrigger.setColumnWidth("termino", 120);
		tblTrigger.setColumnWidth("ultEjec", 120);
		tblTrigger.setColumnWidth("sigEjec", 120);
		tblTrigger.setColumnWidth("estado", 70);
		
		tblTrigger.setColumnHeader("grupo", "Grupo");
		tblTrigger.setColumnHeader("tipo", "Tipo");
		tblTrigger.setColumnHeader("nombre", "Nombre");
		tblTrigger.setColumnHeader("prioridad", "Prio.");
		tblTrigger.setColumnHeader("expresion", "Expresión");
		tblTrigger.setColumnHeader("inicio", "Inicio");
		tblTrigger.setColumnHeader("termino", "Término");
		tblTrigger.setColumnHeader("ultEjec", "Últ.Ejecución");
		tblTrigger.setColumnHeader("sigEjec", "Sig.Ejecución");
		tblTrigger.setColumnHeader("estado", "Estado");
		
		int con = 1;
		
		for (QrtzTriggers trigger: listaTrigger){
			QrtzCronTriggers cron = new QrtzCronTriggers();
			cron.setTriggerGroup(trigger.getTriggerGroup());
			cron.setTriggerName(trigger.getTriggerName());
			if(cronExpresion!=null){
				cron.setCronExpression(cronExpresion);
			}
				
			
			List<QrtzCronTriggers> lstCronTrigger = genericoORM.buscarCronTriggers(cron);
			
			for(QrtzCronTriggers cronTrigger:lstCronTrigger){
				Item item = container.addItem(con++);
				item.getItemProperty("grupo").setValue(trigger.getTriggerGroup());
				item.getItemProperty("tipo").setValue(trigger.getTriggerType());
				item.getItemProperty("nombre").setValue(trigger.getTriggerName());
				item.getItemProperty("prioridad").setValue(trigger.getPriority());
				item.getItemProperty("expresion").setValue(cronTrigger.getCronExpression());
				DateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
				item.getItemProperty("inicio").setValue(dateFormat.format(new Date(trigger.getStartTime())));
				item.getItemProperty("termino").setValue(dateFormat.format(new Date(trigger.getEndTime())));
				item.getItemProperty("ultEjec").setValue(dateFormat.format(new Date(trigger.getPrevFireTime())));
				item.getItemProperty("sigEjec").setValue(dateFormat.format(new Date(trigger.getNextFireTime())));
				item.getItemProperty("estado").setValue(trigger.getTriggerState());	
			}
		}
		
		if(flagLimpiar){
			txtFiltroGrupoTrigger.setValue("");
			txtFiltroTipoTrigger.setValue("");
			txtFiltroNombreTrigger.setValue("");
			txtFiltroPrioridadTrigger.setValue("");
			txtFiltroExpresionTrigger.setValue("");
			txtFiltroInicioTrigger.setValue("");
			txtFiltroTerminoTrigger.setValue("");
			txtFiltroUltEjecTrigger.setValue("");
			txtFiltroSigEjecTrigger.setValue("");
			txtFiltroEstadoTrigger.setValue("");
		}
	}
	
	private void habilitarEdicionJob(boolean flag){
		flagNuevoJob = !flag;
		btnEliminarJob.setVisible(flag);
		btnEjecutarJob.setVisible(flag);
		
		if(flag){
			btnGrabarJob.setCaption("Actualizar");
		}
		else{
			btnGrabarJob.setCaption("Crear");
		}
	}
	
	private void habilitarEdicionTrigger(boolean flag){
		flagNuevoTrigger = !flag;
		btnEliminarTrigger.setVisible(flag);
		btnEjecutarTrigger.setVisible(flag);
		
		if(flag){
			btnGrabarTrigger.setCaption("Actualizar");
		}
		else{
			btnGrabarTrigger.setCaption("Crear");
		}
	}
	
	private String formatoFecha(Date fecha) {

		String fechaActualizacion = "";
		String horaActualizacion = "";

		Calendar calFechaAct = Calendar.getInstance();
		calFechaAct.setTimeInMillis(fecha.getTime());
		fechaActualizacion = calFechaAct.get(Calendar.DATE) + "/"
				+ calFechaAct.get(Calendar.MONTH) + "/"
				+ calFechaAct.get(Calendar.YEAR);
		horaActualizacion = calFechaAct.get(Calendar.HOUR) + ":"
				+ calFechaAct.get(Calendar.MINUTE) + ":"
				+ calFechaAct.get(Calendar.SECOND);

		return fechaActualizacion + " " + horaActualizacion;
	}
	
	@Override
	public void valueChange(ValueChangeEvent event) {
		boolean esModoNuevoJob = tblJob.getValue() == null;
		valueChangeJob(esModoNuevoJob);
	}
	
	private void valueChangeJob(boolean esModoNuevoJob){
		if(esModoNuevoJob){
			tblJob.setValue(null);
			habilitarEdicionJob(!esModoNuevoJob);
			
			limpiar(JOB);
			panelTrigger.setVisible(false);
		}else{
			Item item = tblJob.getItem(tblJob.getValue());
			txtGrupoJob.setValue(item.getItemProperty("jobGroup").getValue());
			txtNombreJob.setValue(item.getItemProperty("jobName").getValue());
			txtDescripcionJob.setValue((item.getItemProperty("description").getValue()==null?""
										:item.getItemProperty("description").getValue()));
			txtClaseJob.setValue(item.getItemProperty("jobClassName").getValue());
			
			habilitarEdicionJob(!esModoNuevoJob);
			
			QrtzTriggers trigger = new QrtzTriggers();
			trigger.setJobGroup((String) txtGrupoJob.getValue());
			trigger.setJobName((String) txtNombreJob.getValue());
			
			JobDetail jobDetail = null;
			try {
				jobDetail = scheduler.getJobDetail((String) txtNombreJob.getValue(),
				        (String) txtGrupoJob.getValue());
			} catch (SchedulerException e) {
				logger.error("+++ ERROR OBTENIENDO JOBDETAIL: " + e.getMessage());
				e.printStackTrace();
			}
			
			cargarTablaTrigger(jobDetail, true, null, null);
			panelTrigger.setVisible(true);
			habilitarEdicionTrigger(esModoNuevoJob);
		}
	}
	
	private void valueChangeTrigger(boolean esModoNuevoTrigger){
		if(esModoNuevoTrigger){
			tblTrigger.setValue(null);
			habilitarEdicionTrigger(!esModoNuevoTrigger);
			limpiar(TRIGGER);
		}else{
			Item item = tblTrigger.getItem(tblTrigger.getValue());
			txtGrupoTrigger.setValue(item.getItemProperty("grupo").getValue());
			txtNombreTrigger.setValue(item.getItemProperty("nombre").getValue());
			txtPrioridadTrigger.setValue(item.getItemProperty("prioridad").getValue());
			txtExpresionTrigger.setValue(item.getItemProperty("expresion").getValue());
			
			habilitarEdicionTrigger(!esModoNuevoTrigger);
		}
	}
	
	private void limpiar(String nombre){
		if(nombre.equals(JOB)){
			txtGrupoJob.setValue("");
			txtNombreJob.setValue("");
			txtDescripcionJob.setValue("");
			txtClaseJob.setValue("");
		}else if(nombre.equals(TRIGGER)){
			txtGrupoTrigger.setValue("");
			txtNombreTrigger.setValue("");
			txtPrioridadTrigger.setValue("");
			txtExpresionTrigger.setValue("");
			/*txtCodigoValor.setValue("");
			cboEstadoValor.setValue(null);		
			txtNombreValor.setValue("");
			txtDescripcionValor.setValue("");
			txtOrdenValor.setValue("");
			Item item = tblListas.getItem(tblListas.getValue());
			Lista lista = new Lista();
			lista.setId((Long)item.getItemProperty("id").getValue());
			cboLista.select(lista);*/
		}
	}
	
//	@Override
	public void buttonClick(ClickEvent event) {
		if(event.getButton().equals(btnActualizarEstado)){
			actualizarEstadoScheduler();
		}
		if(event.getButton().equals(btnGrabarJob)){
			grabarJob();
		}
		if(event.getButton().equals(btnEliminarJob)){
			eliminarJob();
		}
		if(event.getButton().equals(btnGrabarTrigger)){
			grabarTrigger();
		}
		if(event.getButton().equals(btnEliminarTrigger)){
			eliminarTrigger();
		}
		if(event.getButton().equals(btnEjecutarTrigger)){
			ejecutarTrigger();
		}
		if(event.getButton().equals(btnIniciarScheduler)){
			iniciarScheduler();
		}
		if(event.getButton().equals(btnDetenerScheduler)){
			detenerScheduler();
		}
		if(event.getButton().equals(btnEjecutarJob)){
			ejecutarJob();
		}
		
	}
	
	/*** ACTUALIZA LA INFORMACION DEL JOB ***/
	private void grabarJob(){
		/*QrtzJobDetails job = new QrtzJobDetails();
		job.setJobGroup((String) txtGrupoJob.getValue());
		job.setJobName((String) txtNombreJob.getValue());
		job.setDescription((String) txtDescripcionJob.getValue());
		job.setJobClassName((String) txtClaseJob.getValue());
		job.setIsDurable(PanelConfigurarTareas.IS_DURABLE);
		job.setIsStateful(PanelConfigurarTareas.IS_STATEFUL);
		job.setIsVolatile(PanelConfigurarTareas.IS_VOLATILE);
		job.setRequestsRecovery(PanelConfigurarTareas.REQUESTS_RECOVERY);
		
		if(flagNuevoJob){
			quartzJobDetailsService.crear(job);
//			listaService.crear(lista);
		}
		else{
			quartzJobDetailsService.actualizar(job);
//			lista.setId(Long.parseLong(lblIdLista.getValue().toString()));
//			listaService.actualizar(lista);
		}*/
		
		if(!validaDatosObligatoriosJob()){
			if(validaCreacionJob()){
				JobDetail jobDetail = null;
				
		    	Class clss = null;
		    	try {
					clss = Class.forName((String) txtClaseJob.getValue());
				} catch (Exception e) {
					getWindow().showNotification("+++ INGRESE UN JOB EXISTENTE: ", Notification.TYPE_ERROR_MESSAGE);
					return;
					//e.printStackTrace();
				}
		    	
		    	jobDetail = new JobDetail();
				jobDetail.setName((String) txtNombreJob.getValue());
				jobDetail.setGroup((String) txtGrupoJob.getValue());
				 
				jobDetail.setJobClass(clss);
				jobDetail.setDescription((String) txtDescripcionJob.getValue());
				jobDetail.setDurability(false);
				jobDetail.setVolatility(false);
				
				try {
					scheduler.addJob(jobDetail, true);	
				} catch (SchedulerException e) {
					logger.error("+++ ERROR AGREGANDO JOB: " + e.getMessage());
					getWindow().showNotification("+++ ERROR AGREGANDO JOB: " + e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					e.printStackTrace();
				}
		    	
		    	cargarTablaJob(null);
		    	limpiar(JOB);
			}else{
				getWindow().showNotification("YA EXISTE UNA TAREA CON EL MISMO NOMBRE Y GRUPO", Notification.TYPE_ERROR_MESSAGE);
			}
		}else{
			getWindow().showNotification("FALTA INGRESAR DATOS OBLIGATORIOS... ", Notification.TYPE_ERROR_MESSAGE);
		}
		
		
	}
	
	private boolean validaDatosObligatoriosJob(){
		if(txtGrupoJob.isRequired() && !StringUtils.isNotBlank((String)txtGrupoJob.getValue())){
			return true;
		}
		if(txtNombreJob.isRequired() && !StringUtils.isNotBlank((String)txtNombreJob.getValue())){
			return true;
		}
		if(txtClaseJob.isRequired() && !StringUtils.isNotBlank((String)txtClaseJob.getValue())){
			return true;
		}
		if(txtDescripcionJob.isRequired() && !StringUtils.isNotBlank((String)txtDescripcionJob.getValue())){
			return true;
		}
		
		return false;
	}
	
	private boolean validaCreacionJob(){
		Item item = tblJob.getItem(tblJob.getValue());
		// SI ACTUALIZAMOS LOS DATOS DEL JOB
		if(!flagNuevoJob && item!=null){
			String nombreJob = (String) item.getItemProperty("jobName").getValue();  
			String grupoJob = (String) item.getItemProperty("jobGroup").getValue();	
			boolean esJob = isEqualsJob(nombreJob, grupoJob, (String) txtNombreJob.getValue(), (String) txtGrupoJob.getValue());
			if(!esJob){
				if(obtenerListaJobDetail()!=null){
					return false;
				}
			}else{
				return true;
			}
		}else{
			if(flagNuevoJob && obtenerListaJobDetail().size()>0){
				return false;
			}else{
				return true;
			}
		}
		return false;
	}
	
	
	private List<QrtzJobDetails> obtenerListaJobDetail(){
		QrtzJobDetails job = new QrtzJobDetails();
		job.setJobGroup((String) txtGrupoJob.getValue());
		job.setJobName((String) txtNombreJob.getValue());
		
		List<QrtzJobDetails> lstJob = genericoORM.buscarJobDetails(job);
		return lstJob;
	}
	
	private boolean isEqualsJob(String oldName, String oldGroup, String newName, String newGroup){
		if(oldName.compareTo(newName)==0 && oldGroup.compareTo(newGroup)==0){
			return true;
		}
		return false;
	}
	
	/*** ACTUALIZA LA INFORMACION DEL TRIGGER ***/
	private void grabarTrigger(){
		try {
			
			if(!validaDatosObligatoriosTrigger()){
				if(validaCreacionTrigger()){
					CronTrigger cronTriggerd = new CronTrigger();
		            cronTriggerd.setName((String)txtNombreTrigger.getValue());
		            cronTriggerd.setGroup((String) txtGrupoTrigger.getValue());
				    cronTriggerd.setCronExpression((String) txtExpresionTrigger.getValue());
		            cronTriggerd.setPriority(Integer.parseInt(txtPrioridadTrigger.getValue().toString()));
		            cronTriggerd.setJobGroup((String) txtGrupoJob.getValue());
		            cronTriggerd.setJobName((String) txtNombreJob.getValue());
		            
		            JobDetail jobDetail = null;
		    		try {
						jobDetail = scheduler.getJobDetail((String) txtNombreJob.getValue(),
						        (String) txtGrupoJob.getValue());
					} catch (SchedulerException e) {
						logger.error("+++ ERROR OBTENIENDO JOBDETAIL: " + e.getMessage());
						e.printStackTrace();
					}
		    		if(flagNuevoTrigger){
		    			scheduler.scheduleJob(cronTriggerd);
		    			logger.info("+++ SE REGISTRO CORRECTAMENTE EL TRIGGER");
		    		}else{
		    			Item item = tblTrigger.getItem(tblTrigger.getValue());
		    			String nombreTrigger = (String) item.getItemProperty("nombre").getValue();  
		    			String grupoTrigger = (String) item.getItemProperty("grupo").getValue();
		    			
		    			scheduler.rescheduleJob(nombreTrigger, grupoTrigger, cronTriggerd);
		    			logger.info("+++ SE ACTUALIZO CORRECTAMENTE EL TRIGGER");
		    		}
		    		cargarTablaTrigger(jobDetail, true, null, null);			
		    		limpiar(TRIGGER);
				}else{
					getWindow().showNotification("YA EXISTE UN TRIGGER CON EL MISMO NOMBRE Y GRUPO", Notification.TYPE_ERROR_MESSAGE);
				}
			}else{
				getWindow().showNotification("FALTA INGRESAR DATOS OBLIGATORIOS... ", Notification.TYPE_ERROR_MESSAGE);
			}
			
		} catch (Exception e) {
			logger.error("+++ OCURRIO UN ERROR AL CREAR TRIGGER: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private boolean validaDatosObligatoriosTrigger(){
		if(txtGrupoTrigger.isRequired() && !StringUtils.isNotBlank((String)txtGrupoTrigger.getValue())){
			return true;
		}
		if(txtNombreTrigger.isRequired() && !StringUtils.isNotBlank((String)txtNombreTrigger.getValue())){
			return true;
		}
		if(txtPrioridadTrigger.isRequired() && !StringUtils.isNotBlank(txtPrioridadTrigger.getValue().toString())){
			return true;
		}
		if(txtExpresionTrigger.isRequired() && !StringUtils.isNotBlank((String)txtExpresionTrigger.getValue())){
			return true;
		}
		
		return false;
	}
	
	private boolean validaCreacionTrigger(){
		Item item = tblTrigger.getItem(tblTrigger.getValue());
		// SI ACTUALIZAMOS LOS DATOS DEL TRIGGER	
		if(!flagNuevoTrigger && item!=null){
			String nombreTrigger = (String) item.getItemProperty("nombre").getValue();  
			String grupoTrigger = (String) item.getItemProperty("grupo").getValue();	
			boolean esTrigger = isEqualsTrigger(nombreTrigger, grupoTrigger, (String) txtNombreTrigger.getValue(), (String) txtGrupoTrigger.getValue());
			if(!esTrigger){
				if(obtenerListaTrigger().size()>0){
					return false;
				}
			}else{
				return true;
			}
		}else{
			if(flagNuevoTrigger && obtenerListaTrigger().size()>0){
				return false;
			}else{
				return true;
			}
		}
		return false;
	}
	
	
	private List<QrtzTriggers> obtenerListaTrigger(){
		QrtzTriggers trigger = new QrtzTriggers();
		trigger.setTriggerName((String) txtNombreTrigger.getValue());
		trigger.setTriggerGroup((String) txtGrupoTrigger.getValue());
		
		List<QrtzTriggers> lstTrigger = genericoORM.buscarTriggers(trigger);
		return lstTrigger;
	}
	
	private boolean isEqualsTrigger(String oldName, String oldGroup, String newName, String newGroup){
		if(oldName.compareTo(newName)==0 && oldGroup.compareTo(newGroup)==0){
			return true;
		}
		return false;
	}
	
	
	private void buscarFiltrosJob(){
		QrtzJobDetails job = new QrtzJobDetails();
		job.setJobGroup((String) txtFiltroGrupoJob.getValue());
		job.setJobName((String) txtFiltroNombreJob.getValue());
		job.setDescription((String) txtFiltroDescripcionJob.getValue());
		job.setJobClassName((String) txtFiltroClaseJob.getValue());
		
		List<QrtzJobDetails> lstJob = genericoORM.buscarJobDetails(job);
		cargarTablaJob(lstJob);
	}
	
	private void buscarFiltrosTrigger(){
		QrtzTriggers trigger = new QrtzTriggers();
		trigger.setJobGroup((String) txtGrupoJob.getValue());
		trigger.setJobName((String) txtNombreJob.getValue());
		trigger.setTriggerGroup((String) txtFiltroGrupoTrigger.getValue());
		trigger.setTriggerName((String) txtFiltroNombreTrigger.getValue());
		trigger.setTriggerType((String) txtFiltroTipoTrigger.getValue());
		trigger.setTriggerState((String) txtFiltroEstadoTrigger.getValue());
		
		if(StringUtils.isNotBlank((String) txtFiltroPrioridadTrigger.getValue()))
				trigger.setPriority(Integer.parseInt(txtFiltroPrioridadTrigger.getValue().toString()));
		
		List<QrtzTriggers> lstTrigger = genericoORM.buscarTriggers(trigger);
		
		String expresion = (StringUtils.isNotBlank((String)txtFiltroExpresionTrigger.getValue())?(String) txtFiltroExpresionTrigger.getValue():null);
					
		
		JobDetail jobDetail = null;
		try {
			jobDetail = scheduler.getJobDetail((String) txtNombreJob.getValue(), (String) txtGrupoJob.getValue());
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL OBTENER JOBDETAIL " + e.getMessage());
			e.printStackTrace();
		}
		cargarTablaTrigger(jobDetail, true, lstTrigger, expresion);
		
	}
	
	private void eliminarJob(){
		final String grupoJob = (String) txtGrupoJob.getValue();
		final String nombreJob = (String) txtNombreJob.getValue();
		
		ConfirmDialog.show(getWindow().getParent() , "¿Está seguro de eliminar el Job?",
		        new ConfirmDialog.Listener() {
			private static final long serialVersionUID = 1L;
			public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                	eliminaJob(grupoJob, nombreJob);
                } 
            }
        });
	}
	
	private void eliminarTrigger(){
		final String grupoTrigger = (String) txtGrupoTrigger.getValue();
		final String nombreTrigger = (String) txtNombreTrigger.getValue();
		
		ConfirmDialog.show(getWindow().getParent() , "¿Está seguro de eliminar el Trigger?",
		        new ConfirmDialog.Listener() {
			private static final long serialVersionUID = 1L;
			public void onClose(ConfirmDialog dialog) {
                if (dialog.isConfirmed()) {
                	eliminaTrigger(grupoTrigger, nombreTrigger);
                } 
            }
        });
	}
	
	private void eliminaJob(String grupoJob, String nombreJob){
		try {
			scheduler.deleteJob(nombreJob, grupoJob);
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL ELIMINAR EL JOB " + e.getMessage());
			e.printStackTrace();
		}
		cargarTablaJob(null);
		
		//ELIMINAR TRIGGERS
		JobDetail jobDetail = null;
		try {
			jobDetail = scheduler.getJobDetail(nombreJob, grupoJob);
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL OBTENER JOBDETAIL " + e.getMessage());
			e.printStackTrace();
		}
		cargarTablaTrigger(jobDetail, true, null, null);
	}
	
	private void eliminaTrigger(String grupoTrigger, String nombreTrigger){
		JobDetail jobDetail = null;
		try {
			Trigger trigger = scheduler.getTrigger(nombreTrigger, grupoTrigger);
			scheduler.unscheduleJob(nombreTrigger, grupoTrigger);
			if(trigger!=null){
				jobDetail = scheduler.getJobDetail(trigger.getJobName(), trigger.getJobGroup());	
			}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL ELIMINAR TRIGGER " + e.getMessage());
			e.printStackTrace();
		}
		cargarTablaTrigger(jobDetail, true, null, null);
	}
	
	private void ejecutarTrigger(){
		try {
    		Trigger trigger = scheduler.getTrigger((String) txtNombreTrigger.getValue(),(String) txtGrupoTrigger.getValue());
    		if(trigger!=null){
    		    scheduler.triggerJob(trigger.getJobName(),trigger.getJobGroup());
    		    logger.info("+++ TRIGGER FUE EJECUTADO CORRECTAMENTE");	
    		    
    		    JobDetail jobDetail = null;
    			try {
    				jobDetail = scheduler.getJobDetail(trigger.getJobName(), trigger.getJobGroup());
    			} catch (SchedulerException e) {
    				logger.error("+++ OCURRIO UN ERROR AL OBTENER JOBDETAIL " + e.getMessage());
    				e.printStackTrace();
    			}
    			cargarTablaTrigger(jobDetail, true, null, null);
    		}else{
    			logger.error("+++ TRIGGER NO PUEDE SER EJECUTADO");	
    		}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL EJECUTAR TRIGGER " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private void ejecutarJob(){
		try {
			JobDetail jobDetail = null;
			try {
				jobDetail = scheduler.getJobDetail((String)txtNombreJob.getValue(), (String) txtGrupoJob.getValue());
			} catch (SchedulerException e) {
				logger.error("+++ OCURRIO UN ERROR AL OBTENER JOBDETAIL " + e.getMessage());
				e.printStackTrace();
			}
			
    		if(jobDetail!=null){
    		    scheduler.triggerJob(jobDetail.getName(),jobDetail.getGroup());
    		    logger.info("+++ JOB FUE EJECUTADO CORRECTAMENTE");
    		    limpiar(JOB);
    		}else{
    			logger.error("+++ JOB NO PUEDE SER EJECUTADO");	
    		}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL EJECUTAR JOB " + e.getMessage());
			getWindow().showNotification("+++ OCURRIÃ“ UN ERROR AL EJECUTAR JOB " + e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
	
	private void validarScheduler(){
		try {
//			System.out.println("++++ EL SCHEDULER ESTA : " +scheduler.isStarted());
//			System.out.println("++++ EL SCHEDULER ESTA : " +scheduler.isInStandbyMode());
//			if(scheduler.isShutdown()){
			if(scheduler.isInStandbyMode()){
				btnIniciarScheduler.setEnabled(true);
				btnDetenerScheduler.setEnabled(false);
			}else{
				btnIniciarScheduler.setEnabled(false);
				btnDetenerScheduler.setEnabled(true);
			}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR VALIDANDO SCHEDULER " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private void actualizarEstadoScheduler(){
		validarScheduler();
	}
	
	private void iniciarScheduler(){
		try {
//			if(scheduler.isShutdown()){
			if(scheduler.isInStandbyMode()){
				scheduler.start();
				btnIniciarScheduler.setEnabled(false);
				btnDetenerScheduler.setEnabled(true);
			}else{
				logger.error("+++ SCHEDULER SE ENCUENTRA ACTIVO");
			}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL INICIAR SCHEDULER " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	private void detenerScheduler(){
		try {
			if(scheduler.isStarted()){
				scheduler.standby();
				btnIniciarScheduler.setEnabled(true);
				btnDetenerScheduler.setEnabled(false);
			}else{
				logger.error("+++ SCHEDULER SE ENCUENTRA DETENIDO");
			}
		} catch (SchedulerException e) {
			logger.error("+++ OCURRIO UN ERROR AL DETENER SCHEDULER " + e.getMessage());
			e.printStackTrace();
		}
	
	}
}
